const { getOrderInfo, updateOrder } = require('../../model/order')
const { getOne } = require('../../utils/dbTools')
const fs = require('fs')
const tableName = 'orders'

// 引入支付模块
const { AlipaySdk } = require('alipay-sdk')

//支付宝支付返回form表单
const alipay = async (req, res) => {
	const output = { code: 200, msg: '操作成功' }
	// 获取支付基本参数  子订单交易号 总支付金额
	let { out_trade_no, type } = req.body;
	// 验证基本参数
	if (!out_trade_no || !['1', '2', '3'].includes(type + '')) {
		output.code = 500;
		output.msg = "参数错误:缺少支付参数out_trade_no或者type";
		return res.send(output);
	}
	// 通过订单号获取金额
	const { description, total_amount, product } = await getOrderInfo({ out_trade_no })

	if (!total_amount) {
		output.code = 500;
		output.msg = "订单信息不存在";
		return res.send(output);
	}
	// 读取公钥密钥
	const privateKey = fs.readFileSync('./keys/alipay-pravite-key.pem', 'ascii')
	const alipayPublicKey = fs.readFileSync('./keys/alipay.public-key.pem', 'ascii')

	// 实例化客户端
	const alipaySdk = new AlipaySdk({
		// 设置应用 ID
		appId: '9021000140697146',
		// 设置应用私钥
		// privateKey: fs.readFileSync('/keys/alipay-pravite-key.pem', 'ascii'),
		privateKey,//:"MIIEogIBAAKCAQEAg4qjBgA+pNTAI4z2i//ycuckd0diSorWkSkspVz1TG9mZ8Qs84Me3zI4BeSXjj95HpSJB8id4LYLGGB6iunRYHt6Nu4BtrgbttjNVViped6XKYllOTCGLThYUkucN2/cA4FEcgYGmEdFR/frA2mjR/kgSS4QhBEmwcBWHn3rbDNxeIfAKXvZHOALLc1FYaOGi8jBjxcmDTKXCzw/kjOiFLX6beZOKw6bXsybBh6yq5dThf3yFmC5TUpxqF5F08vKpOruTuehJT4ipPY2ySJFYsmdMC53hcatxooRGYF+Y4MBWgv4vbEQNRmfeFjKRFEiTml1MhuBm50zZptCrPYuPQIDAQABAoIBABQn2BcBTpf/KXnJDbYh/8pvdHz6aSs23u3bO0YTWlrd7vkTbDfb7Y0RqtfsUPSw8SQoal7Q9LAL9ONFVUGX1kdMZEuqaITQ7R41VjEv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QxJZ88ztj0VFbIhisjX+GIBWcoPZA=",
		// 设置支付宝公钥
		alipayPublicKey,//: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg4qjBgA+pNTAI4z2i//ycuckd0diSorWkSkspVz1TG9mZ8Qs84Me3zI4BeSXjj95HpSJB8id4LYLGGB6iunRYHt6Nu4BtrgbttjNVViped6XKYllOTCGLThYUkucN2/cA4FEcgYGmEdFR/frA2mjR/kgSS4QhBEmwcBWHn3rbDNxeIfAKXvZHOALLc1FYaOGi8jBjxcmDTKXCzw/kjOiFLX6beZOKw6bXsybBh6yq5dThf3yFmC5TUpxqF5F08vKpOruTuehJT4ipPY2ySJFYsmdMC53hcatxooRGYF+Y4MBWgv4vbEQNRmfeFjKRFEiTml1MhuBm50zZptCrPYuPQIDAQAB",
		// 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
		// keyType: 'PKCS1',
		// 设置网关地址，默认是 https://openapi.alipay.com
		// endpoint: 'https://openapi.alipay.com',
		gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do'
	});


	const bizContent = {
		out_trade_no,
		product_code: "FAST_INSTANT_TRADE_PAY",
		subject: product,
		body: description,
		total_amount,
	};
	let payUrl = 'alipay.trade.page.pay'
	// 根据请求type类型获取请求支付form表单 1是返回PC网站支付; 2是返回手机网站支付; 3是app支付 alipay.trade.app.pay
	if (type == 2) {
		payUrl = 'alipay.trade.wap.pay'
	}
	if (type == 3) {
		payUrl = 'alipay.trade.app.pay'
	}
	// 支付页面接口，返回 HTML 代码片段，内容为 Form 表单
	const html = alipaySdk.pageExecute(payUrl, 'POST', {
		bizContent,
		// 同步跳转地址
		returnUrl: 'http://localhost:8080',
		notifyUrl: 'http://5173dl4199.eicp.vip/front/alipayNotifyUrl',
	});
	output.data = html
	res.send(output);
}


// 异步回调地址: 支付平台一般会多次请求(8次), 直到响应了'success'
const alipayNotifyUrl = async (req, res) => {
	const output = { code: 200, msg: 'success' }
	// {trade_status:'TRADE_SUCCESS'}
	const { out_trade_no, trade_no, buyer_pay_amount: pay_amount, trade_status } = req.body
	// 记录异步日志
	// fs.writeFileSync(`./alipay.log`, JSON.stringify(payload))
	if (trade_status == 'TRADE_SUCCESS') {
		// 获取订单id
		const result = await getOne(tableName, { out_trade_no })
		if (result) {
			const { id } = result
			// 支付时间: 生成mysql datetime
			const pay_time = new Date().toISOString()
			await updateOrder({ id, trade_no, pay_amount, pay_status: 1, pay_time })
		}
	}
	res.send(output.msg);
}

module.exports = {
	alipay, alipayNotifyUrl
}